package huachenxing.mimi520.brower.widgets
{
	import com.cambright.lotusroot.Widget;
	import com.cambright.stack.components.AlignmentLayoutComponent;
	import com.cambright.stack.components.layout.Alignment;
	import com.cambright.stack.components.layout.Direction;
	import com.cambright.stack.components.layout.Element;
	import com.cambright.stack.components.layout.Margin;
	
	import flash.display.NativeWindow;
	import flash.display.NativeWindowInitOptions;
	import flash.display.Screen;
	import flash.display.StageAlign;
	import flash.display.StageScaleMode;
	import flash.events.Event;
	import flash.events.TimerEvent;
	import flash.filesystem.File;
	import flash.geom.Rectangle;
	import flash.html.HTMLLoader;
	import flash.net.URLRequest;
	import flash.utils.Timer;
	
	import mx.utils.StringUtil;
	
	import huachenxing.mimi520.brower.URL;
	import huachenxing.mimi520.option.models.AccountModel;
	import huachenxing.mimi520.option.models.QueryModel;
	import huachenxing.mimi520.option.models.WorkerModel;
	import huachenxing.mimi520.skin.Text;
	
	public class WorkWidget extends Widget
	{
		private var _span:Number;
		private var _brower:HTMLLoader;
		
		override protected function invoke():void
		{
			super.invoke();
			
			if(File.applicationDirectory.resolvePath("debug").exists)
				_brower = HTMLLoader.createRootWindow(true, new NativeWindowInitOptions(), true);
			else _brower = HTMLLoader.createRootWindow(false);
			
			_brower.window.alert = trace;
			_brower.window.close = function():void {};
			_brower.window.print = function():void {};
			_brower.addEventListener(Event.COMPLETE, _onComplete);
			_brower.useCache = false;
			_brower.load(new URLRequest(URL.STOP));
			
			_timeoutTimer.addEventListener(TimerEvent.TIMER, _onTimeout);
			_timeoutTimer.addEventListener(TimerEvent.TIMER_COMPLETE, _onTimeout2);
			
			_queryTimer.addEventListener(TimerEvent.TIMER, _query);
			_answerTimer.addEventListener(TimerEvent.TIMER_COMPLETE, _answer);
		}
		
		override protected function enable():void
		{
			WorkerModel.fromConfig();
			AccountModel.fromConfig();
			QueryModel.fromConfig();
			
			_locate(URL.LOGOUT);
		}
		
		override protected function disable():void
		{
			_queryTimer.stop();
			_answerTimer.stop();
			_timeoutTimer.stop();
			
			_doneVec.length = 0;
			
			_brower.load(new URLRequest(URL.STOP));
		}
		
		private function _alert(msg:String):void
		{
			trace("[MSG] " + msg);
			
			var text:Text = new Text(msg);
			text.color = 0x707c89;
			
			var windowOptions:NativeWindowInitOptions = new NativeWindowInitOptions();
			windowOptions.maximizable = false;
			windowOptions.minimizable = false;
			windowOptions.resizable = false;
			
			var window:NativeWindow = new NativeWindow(windowOptions);
			window.alwaysInFront = true;
			var bounds:Rectangle = Screen.mainScreen.visibleBounds;
			window.width = 300;
			window.height = 200;
			window.x = (bounds.width - window.width) * .5;
			window.y = (bounds.height - window.height) * .5;
			window.stage.scaleMode = StageScaleMode.NO_SCALE;
			window.stage.align = StageAlign.TOP_LEFT;
			
			var layout:AlignmentLayoutComponent = addComponent(AlignmentLayoutComponent);
			layout.direction = Direction.HORIZONTAL;
			layout.alignment = Alignment.MIDDLE_CENTER;
			layout.target = window.stage;
			layout.margin = new Margin(20, 20, 20, 20);
			layout.add(new Element(text));
			layout.enabled = true;
			
			window.activate();
			
			enabled = false;
		}
		
		private function _onTimeout(event:TimerEvent):void
		{
			_brower.reload();
		}
		
		private function _onTimeout2(event:TimerEvent):void
		{
			enabled = false;
			
			_alert("网络请求超时，请检查相关配置后重新运行。");
		}
		
		private var _timeoutTimer:Timer = new Timer(20000, WorkerModel.retry);
		private function _locate(url:String):void
		{
			_brower.load(new URLRequest(url));
			_timeoutTimer.reset();
			_timeoutTimer.start();
		}
		
		private function _onComplete(event:Event):void
		{
			trace("[Location] " + _brower.location);
			
			_timeoutTimer.stop();
			
			if(false) throw ReferenceError("?????");
			else if(_router(URL.INDEX)) _index();
			else if(_router(URL.LOGIN)) _login();
			else if(_router(URL.QUERY, true)) _getAsks();
			else if(_router(URL.QUESTION, true)) _submit();
		}
		
		private function _getInput(name:String):Object
		{
			var inputs:Object = _dom.getElementsByTagName("input");
			for(var i:int = 0; i < inputs.length; ++ i)
			{
				var input:Object = inputs[i];
				if(input.name == name) return input;
			}
			throw ReferenceError("not found input");
		}
		
		private function get _click():Object
		{
			var evt:Object = _dom.createEvent("MouseEvents");
			evt.initEvent("click",true,true);
			return evt;
		}
		
		private function _router(url:String, like:Boolean = false):Boolean
		{
			var location:String = _brower.location;
			var arr:Array = location.split("?");
			location = arr[0];
			if(location.charAt(location.length - 1) == "/")
				location = location.substr(0, location.length - 1);
			if(like)
				return location.indexOf(url) > -1;
			else return location == url;
		}
		
		private function get _dom():Object
		{
			return _brower.window.document;
		}
		
		private function _login():void
		{
			_brower.window.ShowMsg = _loginResponse;
			var username:String = AccountModel.username;
			var password:String = AccountModel.password;
			trace("[Login] username: " + username + " | password: " + password);
			var usernameInput:Object = _getInput("username");
			usernameInput.value = username;
			var passwordInput:Object = _getInput("password");
			passwordInput.value = password;
			var loginButton:Object = _dom.getElementById("submitlogin");
			loginButton.click();
			
			_timeoutTimer.reset();
			_timeoutTimer.start();
		}
		
		private function _loginResponse(msg:String = "", type:int = 0, time:* = null, callback:* = null):void
		{
			_timeoutTimer.stop();
			if(type == 2) _query(null);
			else if(type == 0) _alert(msg);
		}
		
		private function _index():void
		{
			_locate(URL.LOGIN);
		}
		
		private var _spanIndex:int = -1;
		private var _queryURL:String;
		private var _queryIndex:uint;
		private var _queryCount:uint;
		private var _queryTimer:Timer = new Timer(WorkerModel.query * 1000, 1);
		private function _query(event:TimerEvent):void
		{
			if(event == null)
			{
				if(QueryModel.monthVec.length == 0)
				{
					_alert("尚未设置查询时间");
					return;
				}
				
				++_spanIndex;
				if(_spanIndex >= QueryModel.monthVec.length)
					_spanIndex = 0;
				
				var date:Date = new Date();
				date.setTime(QueryModel.monthVec[_spanIndex].getTime());
				date.setDate(1);
				date.setHours(0, 0, 0, 0);
				trace("[Span] " + date.toString());
				_span = date.getTime();
				
				_queryURL = URL.QUERY + StringUtil.substitute(URL.QUERY_ARGS, 11, "", date.fullYear, (date.month + 101).toString().substr(1), 1);
				_queryIndex = 0;
				_queryCount = 1;
				_workVec.length = 0;
			}
			
			if(++ _queryIndex > _queryCount)
			{
				_getAsksComplete();
				return;
			}
			
			_queryTimer.reset();
			_queryTimer.start();
			
			_locate(_queryURL+ _queryIndex + ".html");
		}
		
		private function _getAsks():void
		{
			var paging:Object = _dom.getElementsByClassName("paging")[0];
			paging = paging.lastElementChild;
			var tempStr:String = paging.innerHTML;
			var allAsks:uint = uint(tempStr.substring(1, tempStr.indexOf("条")));
			var prePage:uint = uint(tempStr.substring(tempStr.indexOf("页") + 1, tempStr.lastIndexOf("条")));
			_queryCount = Math.ceil(allAsks / prePage);
			
			var asks:Object = _dom.getElementsByClassName("list-main-l");
			for(var i:int = 0; i < asks.length; ++ i)
			{
				var ask:Object = asks[i].parentNode;
				var askInfo:AskInfo = _getAskInfo(ask);
				if(askInfo.date.getTime() < _span && !askInfo.worry)
				{
					_getAsksComplete();
					return;
				}
				if(askInfo.answer != 0 && _doneVec.indexOf(askInfo.id) == -1) 
				{
					_workVec.push(askInfo);
				}
			}
			
			_query(new TimerEvent(TimerEvent.TIMER_COMPLETE));
		}
		
		private function _getAskInfo(li:Object):AskInfo
		{
			var info:AskInfo = new AskInfo();
			
			var answer:Object = li.getElementsByClassName("q-num")[0];
			info.answer = uint(answer.innerHTML);
			
			var a:Object = li.getElementsByTagName("a")[0];
			info.title = a.title;
			var href:String = a.href;
			info.id = uint(href.substring(href.indexOf("_") + 1, href.lastIndexOf(".html")));
			
			var date:String = li.getElementsByClassName("fr")[0].innerHTML;
			var arr:Array = date.split("-");
			info.date = new Date(int(arr[0]), int(arr[1]) - 1, int(arr[2]));
			
			var region:Object = li.getElementsByClassName("area");
			if(region.length > 0)
			{
				region = region[0];
				info.region = region.innerHTML;
			}

			info.worry = li.getElementsByClassName("worry-ico").length > 0;
			return info;
		}
		
		private var _doneVec:Vector.<uint> = new Vector.<uint>();
		private var _workVec:Vector.<AskInfo> = new Vector.<AskInfo>();
		private function _getAsksComplete():void
		{
			_queryTimer.stop();
			_answerTimer.start();
		}
		
		private var _answerTimer:Timer = new Timer(WorkerModel.answer * 1000, 1);
		private function _answer(event:TimerEvent):void
		{
			if(_workVec.length > 0)
			{
				_lastQuestionLocation = null;
				var askInfo:AskInfo = _workVec.shift();
				var url:String = URL.QUESTION;
				url += askInfo.id + ".html";
				
				_answerTimer.reset();
				_answerTimer.start();
				
				_locate(url);
			}
			else 
			{
				_answerTimer.stop();
				_query(null);
			}
		}
		
		private var _lastQuestionLocation:String;
		private function _submit():void
		{
			if(_lastQuestionLocation == _brower.location)
				return;
			_lastQuestionLocation = _brower.location;	
			
			var submitButton:Object = _dom.getElementById("answersubmit");
			
			if(submitButton != null)
			{
				var answerList:Object = _dom.getElementsByClassName("list-2");
				if(answerList.length > 0)
				{
					answerList = answerList[0];
					var answers:Object = answerList.getElementsByTagName("li");
					var usedContent:String = "";
					for(var i:int = 0; i < answers.length; ++ i)
					{
						var answer:Object = answers[i];
						var p:Object = answer.getElementsByTagName("article")[0].getElementsByTagName("p")[1];
						var content:String = p.innerHTML;
						if(content.length > usedContent.length)
							usedContent = content;
					}
					
					usedContent = usedContent.replace("<br>", "\r");
					usedContent += "\r";
					
					var textArea:Object = _dom.getElementsByTagName("textarea")[0];
					textArea.innerHTML = usedContent;
					
					var strTemp:String = _lastQuestionLocation.replace(URL.QUESTION, "");
					var questId:uint = uint(strTemp.replace(".html", ""));
					_doneVec.push(questId);
					
					submitButton.click();
				}
			}
		}
	}
}

class AskInfo
{
	public var id:uint;
	public var title:String;
	public var region:String;
	public var date:Date;
	public var answer:uint;
	public var worry:Boolean;
}